#!coding=utf-8
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from weixin.api.common import getWebAccToken
from weixin.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.http.response import HttpResponse

def memview(request):  
    code=request.GET.get("code");
    openid=request.session.get('openid',False)
    if openid == False:
        openid=getWebAccToken(code)
        request.session['openid']=openid
    try:
        user=User.objects.get(openid=openid);
        params={'balance':user.balance,'score':user.score,'openid':openid}
    except ObjectDoesNotExist:
        User(openid=openid).save()
        params={'balance':'0','score':'0','openid':openid}
    template='membercenter.html'
    return render_to_response(template,params,context_instance=RequestContext(request))

def meminfo(request): 
    openid=request.GET.get("openid");
    try:
        user=User.objects.get(openid=openid);
        params={'user':user}
    except ObjectDoesNotExist:
        user=User(openid=openid)
        user.save()
        params={'user':user}
    template='adduserinfo.html'
    return render_to_response(template,params,context_instance=RequestContext(request))
   
def adduserinfo(request):
    ContactName=request.POST.get('ContactName')
    Mobile=request.POST.get('Mobile')
    Sender=request.POST.get('Sender')
    Address=request.POST.get('Address')
    openid=request.POST.get('openid')
    try:
        user=User.objects.get(openid=openid);
        user.address=Address;
        user.telephone=Mobile;
        user.nickname=ContactName;
        user.city=Sender;
        user.save();
    except ObjectDoesNotExist:
        User(openid=openid,city=Sender,nickname=ContactName,telephone=Mobile,address=Address).save();
        
    return HttpResponse("true");

def privilege(request):
    template='privilege.html'
    return render_to_response(template,context_instance=RequestContext(request))
        
        
        
        
        
